﻿using Max.PH4_2102A.Shopping.DTO;
using Max.PH4_2102A.Shopping.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH4_2102A.Shopping.API.Controllers
{
    /// <summary>
    /// SPU控制器
    /// </summary>
    [Route("spu")]
    [ApiController]
    public class SPUController : ControllerBase
    {
        ISPUService _service;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="service"></param>
        public SPUController(ISPUService service)
        {
            _service = service;
        }

        /// <summary>
        /// 获取SKU列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get()
        {
            ResponseResultDto response = new ResponseResultDto();

            var result = _service.GetSKUList();
            response.Data = result;

            return Ok(response);
        }


        /// <summary>
        /// 添加产品
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult InsertProudct(ProductInputDto dto)
        {
            ResponseResultDto response = new ResponseResultDto();

            int data = _service.AddProduct(dto); 
            response.Data = data;

            return Ok(response);
        }

        /// <summary>
        /// 上传sku图片
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload")]
        public IActionResult UploadImage(string no)
        {
            ResponseResultDto response = new();

            List<string> fileList = new List<string>();
            var files = Request.Form.Files;

            if(files != null)
            {
                foreach (var item in files)
                {
                    var path = $"wwwroot/{item.FileName}";
                    using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        item.CopyTo(stream);
                        fileList.Add(path);
                    }
                }
            }

            response.Data = new { no, imageUrl = fileList };

            return Ok(response);
        }
    }


}
